﻿using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace curbside.Core.Utility.IO
{
    /// <summary>
    /// 文件操作帮助类
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 检测文件是否有写权限
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>文件可写，返回true；否则，返回false</returns>
        public static bool TestReadWriteAccces(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            if (!fi.IsReadOnly)
            {
                return HasAccces(fi, FileSystemRights.Modify);
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 检测文件是否有指定的访问权限
        /// </summary>
        /// <param name="fileInfo">文件对象</param>
        /// <param name="fileSystemRights">文件访问权限</param>
        /// <returns>文件有指定的访问权限，返回true；否则，返回false</returns>
        public static bool HasAccces(FileInfo fileInfo, FileSystemRights fileSystemRights)
        {
            string identityName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToUpper();

            AuthorizationRuleCollection authorizationRuleCollection = fileInfo.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount));

            foreach (FileSystemAccessRule fileSystemAccessRule in authorizationRuleCollection)
            {
                if (identityName == fileSystemAccessRule.IdentityReference.Value.ToUpper())
                    return AccessControlType.Allow == fileSystemAccessRule.AccessControlType && fileSystemRights == (fileSystemAccessRule.FileSystemRights & fileSystemRights);
            }

            return false;
        }
    }
}
